<?php

namespace App\Models;

use App\Models\BaseModel;

/**
 * 角色权限关联模型
 */
class RolePermission extends BaseModel
{
    protected $table = 'role_permissions';

    /**
     * 获取表字段
     * @return array
     */
    protected function columns(): array
    {
        return [
            'id',
            'role_id',
            'permission_id',
            'created_at',
            'updated_at',
            'deleted_at'
        ];
    }

    protected function buildQuery(array $params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = parent::buildQuery($params);

        if (!empty($params['permission_ids'])) {
            $query->whereIn('permission_id', $params['permission_ids']);
        }
        return $query;
    }

    /**
     * 关联角色
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function role()
    {
        return $this->belongsTo(Role::class, 'role_id', 'id');
    }

    /**
     * 关联权限
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function permission()
    {
        return $this->belongsTo(Permission::class, 'permission_id', 'id');
    }

    /**
     * 获取角色权限分组名称
     * @param int $roleId 角色ID
     * @return array
     */
    public function getRolePermissionsGroupName(int $roleId): array
    {
        return $this->select('permissions.module')
            ->join('permissions', 'role_permissions.permission_id', '=', 'permissions.id')
            ->where('role_permissions.role_id', $roleId)
            ->distinct()
            ->pluck('permissions.module')
            ->toArray();
    }



    /**
     * 根据角色ID数组获取权限码
     * @param array $roleIds 角色ID数组
     * @return array
     */
    public function getAdminPermissionsByRoleIds(array $roleIds): array
    {
        if (empty($roleIds)) {
            return [];
        }

        return $this->select('permissions.slug', 'permissions.module')
            ->join('permissions', 'role_permissions.permission_id', '=', 'permissions.id')
            ->whereIn('role_permissions.role_id', $roleIds)
            ->get()
            ->toArray();
    }
}
